package handler

import (
	"context"
	"fmt"
	"gitee.com/DonHz/electronic-business-systems/mxshop_srvs/goods_srv/global"
	"gitee.com/DonHz/electronic-business-systems/mxshop_srvs/goods_srv/model"
	"gitee.com/DonHz/electronic-business-systems/mxshop_srvs/goods_srv/proto"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
)

func (s *GoodsServer) BrandList(ctx context.Context, req *proto.BrandFilterRequest) (*proto.BrandListResponse, error) {
	var brandListResp proto.BrandListResponse
	var brands []model.Brands

	res := global.DB.Scopes(Paginate(int(req.Pages), int(req.PagePerNums))).Find(&brands)
	if res.Error != nil {
		return nil, res.Error
	}
	var resp []*proto.BrandInfoResponse
	for _, brand := range brands {
		resp = append(resp, &proto.BrandInfoResponse{
			Id:   int64(brand.ID),
			Name: brand.Name,
			Logo: brand.Logo,
		})
	}
	brandListResp.Data = resp
	var total int64
	global.DB.Model(&model.Brands{}).Count(&total)
	fmt.Println(total)
	brandListResp.Total = int32(total)
	return &brandListResp, nil
}

func (s *GoodsServer) CreateBrand(ctx context.Context, req *proto.BrandRequest) (*proto.BrandInfoResponse, error) {
	//查一下是否存在
	if res := global.DB.Where(&model.Brands{Name: req.Name}).First(&model.Brands{}); res.RowsAffected == 1 {
		return nil, status.Error(codes.AlreadyExists, "品牌已存在")
	}
	brand := &model.Brands{
		Name: req.Name,
		Logo: req.Logo,
	}
	global.DB.Save(brand)
	return &proto.BrandInfoResponse{Id: int64(brand.ID)}, nil
}
func (s *GoodsServer) DeleteBrand(ctx context.Context, req *proto.BrandRequest) (*emptypb.Empty, error) {
	if res := global.DB.WithContext(ctx).Where("name=?", req.Name).Delete(&model.Brands{}); res.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "品牌不存在")
	}
	return &emptypb.Empty{}, nil
}
func (s *GoodsServer) UpdateBrand(ctx context.Context, req *proto.BrandRequest) (*emptypb.Empty, error) {
	brands := model.Brands{}
	if res := global.DB.WithContext(ctx).Find(&brands); res.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "品牌不存在")
	}
	if req.Name != "" {
		brands.Name = req.Name
	}
	if req.Logo != "" {
		brands.Logo = req.Logo
	}
	global.DB.WithContext(ctx).Save(&brands)
	return &emptypb.Empty{}, nil
}
